package priv.lhy.common.utils;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.type.TypeReference;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * author: lihy
 * date: 2019/4/12 11:59
 * description:
 */
public class JsonUtil {

    private final static ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = new ObjectMapper();
        OBJECT_MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    /**
     * JSON字符串转java对象
     *
     * @param json JSON字符串
     * @param clazz   对象类型
     * @return
     */
    public static <T> T json2Object(String json, Class<?> clazz) throws IOException {
        return (T) OBJECT_MAPPER.readValue(json, clazz);
    }

    /**
     * JSON字符串转换为java泛型对象，主要解决List，Map等集合的转换
     *
     * @param json JSON字符串
     * @param tr      TypeReference 泛型类型，例如：new TypeReference<List<Object> >(){}
     * @param <T>     List对象列表
     * @return
     */
    public static <T> T json2GenericObject(String json, TypeReference<T> tr) throws IOException {
        //有属性不能映射成PO时不报错
        OBJECT_MAPPER.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return (T) OBJECT_MAPPER.readValue(json, tr);
    }

    /**
     * java对象转JSON字符串
     *
     * @param object java对象，可以是对象、数组、List、Map等
     * @return JSON字符串
     */
    public static String Object2Json(Object object) throws IOException {
        OBJECT_MAPPER.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        OBJECT_MAPPER.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
        return OBJECT_MAPPER.writeValueAsString(object);
    }
}
